package com.lingz.manager.modules.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingz.manager.modules.wuxue.mapper.DailyInsectCatchDataMapper;
import com.lingz.manager.modules.wuxue.mapper.DeviceInfoMapper;
import com.lingz.manager.modules.wuxue.mapper.RealTimeWeatherMapper;
import com.lingz.manager.modules.wuxue.entity.DailyInsectCatchData;
import com.lingz.manager.modules.wuxue.entity.DeviceInfo;
import com.lingz.manager.modules.wuxue.entity.RealTimeWeather;
import com.lingz.manager.modules.wuxue.utils.SendRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @className: NiuKangTask
 * @author: caiyixun
 * @description: 纽康开放协议定时任务类
 * @date: 2023/11/30 15:43
 * @version: 1.0
 */

@Component
@Slf4j
public class NiuKangTask {

//    @Value("${niukang.insect-catch}")
    String insectCatchUrl = "http://www.smtrap.com/niukang/openapi/getDailyCountInfo";

//    @Value("${niukang.real-time-weather}")
    String realTimeWeather = "http://www.smtrap.com/niukang/openapi/getWeatherByGateway";

    private static final String username = "18507256672";
    private static final String password = "hfyw7852";
    private static final String NIUKANG = "纽康";

    @Autowired
    private DailyInsectCatchDataMapper dailyInsectCatchDataMapper;

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Autowired
    private RealTimeWeatherMapper realTimeWeatherMapper;

    @Scheduled(cron = "0 0 0 * * ?")
    public void insertDailyInsectCatchData() throws IOException {
        //获取当前日期
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String nowDate = today.format(formatter);

        //get请求访问的url
        String url = insectCatchUrl +
                "?username=" + username +
                "&password=" + password +
                "&date=" + nowDate;
        System.out.println(url);

        //请求访问url获取json数据
        SendRequest request = new SendRequest();
        String jsonResponse = request.sendGet(url);
        System.out.println(jsonResponse);

        //读取json转为JsonNode 获取数据
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode root = objectMapper.readTree(jsonResponse);

        //获取result[]中数据
        JsonNode resultNodes = root.get("result");
        if (resultNodes.isArray()) {
            for (JsonNode resultNode : resultNodes) {
                String date = resultNode.get("date").asText();
                int count = resultNode.get("count").asInt();

                JsonNode deviceNode = resultNode.get("device");
                String trapperId = deviceNode.get("trapperId").asText();
                String location = deviceNode.get("location").asText();
                String deviceId = deviceNode.get("deviceId").asText();
                int trapIndex = deviceNode.get("trapIndex").asInt();
                String trapperName = deviceNode.get("trapperName").asText();

                DailyInsectCatchData dailyInsectCatchData = new DailyInsectCatchData();
                dailyInsectCatchData.setDate(date);
                dailyInsectCatchData.setCount(count);
                dailyInsectCatchData.setTrapperId(trapperId);
                dailyInsectCatchData.setLocation(location);
                dailyInsectCatchData.setDeviceId(deviceId);
                dailyInsectCatchData.setTrapIndex(trapIndex);
                dailyInsectCatchData.setTrapperName(trapperName);

                //入库
                log.info(date+" 捕虫设备"+deviceId+"准备入库");
                dailyInsectCatchDataMapper.insert(dailyInsectCatchData);
                log.info("入库成功！");
            }
        }
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void insertRealTimeWeatherData() throws IOException, InterruptedException {
        //获取纽康传感器元数据信息
        LambdaQueryWrapper<DeviceInfo> wrapper = Wrappers.lambdaQuery(DeviceInfo.class);
        wrapper.eq(DeviceInfo::getFactory, NIUKANG);
        List<DeviceInfo> deviceInfoList = deviceInfoMapper.selectList(wrapper);
        System.out.println(deviceInfoList);

        //根据
        for (DeviceInfo deviceInfo : deviceInfoList) {
            //get请求额url
            String url = realTimeWeather +
                    "?username=" + username +
                    "&password=" + password +
                    "&deviceId=" + deviceInfo.getDeviceId();
            System.out.println(url);

            Thread.sleep(10000);

            //请求访问url获取json数据
            SendRequest request = new SendRequest();
            String jsonResponse = request.sendGet(url);
            System.out.println(jsonResponse);

            //读取json转为JsonNode 获取数据
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode root = objectMapper.readTree(jsonResponse);

            //提取数据
            JsonNode resultNode = root.get("result");
            if (resultNode != null) {
                String temperatureValue = resultNode.get("temperature").asText();
                String humidity = resultNode.get("humidity").asText();
                String uploadDate = resultNode.get("upload_date").asText();

                RealTimeWeather realTimeWeather = new RealTimeWeather();
                realTimeWeather.setDeviceId(deviceInfo.getDeviceId());
                realTimeWeather.setTemperature(temperatureValue);
                realTimeWeather.setHumidity(humidity);
                realTimeWeather.setUploadDate(uploadDate);

                //入库
                log.info(humidity+" 设备"+deviceInfo.getDeviceId()+"实时气象数据准备入库");
                realTimeWeatherMapper.insert(realTimeWeather);
                log.info("入库成功！");
            }

        }


    }


}
